<?php
if(!defined('IN_BSTO')){ die('[ERROR] You cannot load this page directly !!!'); }

Class UserManager{
	private $db = null;


	function __construct($db)
	{
		$this->db = $db;
		define('SESSION_KEY', 'userid');
	}
	 
	function getAll()
	{
		//$this->db->startConnection();
		$query = 'SELECT * FROM user WHERE status=1;';
		$objectArray = $this->db->get_data($query, 'user');
		//$this->db->closeConnection();
		return $objectArray;
	}

	function getNum()
	{
		$query = 'SELECT COUNT(*) FROM user WHERE status=1;';
		$result = mysql_fetch_row($this->db->dbQuery($query));
		$max = intval($result[0]);
		return $max;
	}

	function getSome($start, $num)
	{
		if($start >= 0){
			//$this->db->startConnection();
			$query = 'SELECT * FROM user WHERE status=1 LIMIT '.$start.', '.$num. ';';
			$objectArray = $this->db->get_data($query, 'user');
			//$this->db->closeConnection();
			return $objectArray;
		}
	}

	/**
	 * Get a user from database. Return the first one if many users match.
	 * Throw exception if no data found.
	 */

	function get($attr, $value)
	{
		//$this->db->startConnection();
		$query = 'SELECT * FROM user WHERE ' . $attr . ' = ' . var_export($value, true) .' AND status=1;';
		$objectArray = $this->db->get_data($query, 'user');
		//$this->db->closeConnection();
		if (empty($objectArray)) {
			//echo "Does not exist.";
			throw new Exception('Does not exist.');
		}
		return $objectArray[0];
	}

	function filter($attr, $value)
	{
		$query = 'SELECT * FROM user WHERE ' . $attr . ' = ' . var_export($value, true) .' AND status=1;';
		return $this->db->get_data($query, 'user');
	}

	/**
	 * Create an instance object and save it into database.
	 */

	function create($username, $password, $email, $phone='', $company='', $address='', $status=0, $type='Normal', $fbid='', $fullname='', $avatar='')
	{
		$user =  new User($this->db);
		$user->init($username, $password, $email, $phone, $company, $address, $status, $type, $fbid, $fullname, $avatar);
		$user->save();
		return $user;
	}

	/**
	 * Return user if username and password is valid.
	 */

	function authenticate($username,$password)
	{
		$user = $this->get('username', $username);
		if ($user->checkPassword($password)){
			return $user;
		}
		return NULL;
	}

	//tubaduc comment
	function login($user)
	{	
		if($user->get('status') == 0){
			return false;
		} else {
			$this->logout();
			$_SESSION[SESSION_KEY] = $user->get('uid');			
			return true;
		}
	}

	function logout()
	{		
		if(isset($_SESSION[SESSION_KEY])){
			unset($_SESSION[SESSION_KEY]);
		}		
	}

	/**
	 * Return the current user. Return NULL if user not exist.
	 */

	function getCurrentUser()
	{
		if(isset($_SESSION[SESSION_KEY])){
			try {
				$user = $this->get('uid', $_SESSION[SESSION_KEY]);				
				return $user;
			} catch (Exception $e){
				return NULL;
			}
		}
		else {
			return null;
		}


	}
	function checkCookie()
	{
		if(isset($_COOKIE['username'])){
			// validate
			return true;
		}
		else return false;
	}
	function delete($id)
	{
		if ($this->db != null) {
			//$this->db->startConnection();
			$query = 'UPDATE user
				SET status = 0
				WHERE uid = ' . var_export($id, true) . ';';
			$this->db->dbQuery($query);
			
			$queryBook = 'UPDATE entity
						SET status = 0
						WHERE uid = '.var_export($id, true) . ';';
			$this->db->dbQuery($queryBook);
			//$this->db->closeConnection();
		}
	}
	
	
	public function getAllUserNames()
	{
		$query = "SELECT DISTINCT u.username AS `name`
				  FROM user AS u
				  WHERE u.status != 0";		
		$result = $this->db->getMixedData($query);
		return $result;
	}
	
    function getTotalUser($to)
    {
        $query = "SELECT COUNT(u.uid) AS num
                         FROM user AS u 
                         WHERE u.datejoin<(DATE_ADD(STR_TO_DATE('$to', '%d-%b-%Y'), INTERVAL 1 DAY))";
        $result = $this->db->getMixedData($query);
        $row = $result[0];
        return $row['num'];
    }
    function bookDeal($uid, $bid, $quantity, $cost, $phone, $address){
    	$insert = "INSERT INTO BILL (nid, uid, quantity, status) VALUES ($bid, $uid, $quantity, 'pending' )";
    	$this->db->dbQuery($insert);
    	$update = "UPDATE USER SET phone = ".var_export($phone, true).", address = ". var_export($address, true) ." WHERE uid = ". $uid ;
    	$this->db->dbQuery($update);
    }
}
?>